import os.path
from typing import Any

import yaml
from injector import inject, singleton
from pydantic import BaseModel, Field

from internal.core.tools.bean import CategoriesBean


@inject
@singleton
class BuiltinCategoryManager(BaseModel):
    category_map: dict[str, Any] = Field(default_factory=dict)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.init_category()

    def get_category(self):
        return self.category_map

    def init_category(self):
        path = os.path.abspath(__file__)
        path_dir = os.path.dirname(path)
        path_join = os.path.join(path_dir, "categories.yaml")
        with open(path_join, "r", encoding="utf-8") as f:
            category_config = yaml.safe_load(f)
            for item in category_config:
                categroy_bean = CategoriesBean(**item)
                icon_path = os.path.join(path_dir, "icons", categroy_bean.icon)
                with open(icon_path, "r", encoding="utf-8") as t:
                    icon = t.read()
                    self.category_map[categroy_bean.icon] = {
                        "bean": categroy_bean,
                        "icon": icon
                    }
